import path from 'path';
import express from 'express';
import swaggerUI from 'swagger-ui-express';
import swaggerDoc from 'swagger-jsdoc';

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: '烟花管理系统',
      version: '1.0.0',
      description: 'node + express + ts + mysql'
    }
  },
  apis: [path.join(__dirname, '../swagger/*.ts'), path.join(__dirname, '../swagger/*.js')]
};

const swaggerJson = (req: any, res: any) => {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerSpec);
};

const swaggerSpec = swaggerDoc(options);

const swaggerInstall = (app: any) => {
  if (!app) {
    app = express();
  }
  // 开放相关接口
  app.get('/swagger.json', swaggerJson);
  // 使用 swaggerSpec 生成 swagger 文档页面，并开放在指定路由
  app.use('/node/api/doc', swaggerUI.serve, swaggerUI.setup(swaggerSpec));
};

export default swaggerInstall;
